package com.foryang.springcloud.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class MyFilter extends ZuulFilter {
    /**
     * 返回四种类型：
     * pre pre-routing过滤，路由前过滤
     * routing 在路由请求时被调用
     * post routing和error过滤器之后被调用
     * error 处理请求发生错误的时候调用
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        System.out.println("http://" + request.getServerName() + ":" + request.getServerPort() + "/" + request.getParameter("uname"));
        if(request.getParameter("uname") == null || request.getParameter("uname") == ""){
            context.setSendZuulResponse(false);             //进行拦截过滤,禁止路由
            context.setResponseStatusCode(403);             //返回状态码
            context.setResponseBody("{\"error\": \"权限不足 \"}");          //返回数据
            context.getResponse().setContentType("application/json;charset=utf-8");    //设置编码，防止中文乱码
            return null;
        }
        return null;
    }
}
